<template>
  <div class="blog-form-container">
    <div class="blog-form-header">
      <h2>编辑博客</h2>
    </div>
    <el-form ref="blogFormRef" :model="blogForm" :rules="blogFormRules" label-width="100px" class="blog-form">
      <el-form-item label="标题" prop="title">
        <el-input v-model="blogForm.title" placeholder="请输入博客标题"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
                  <!-- 修改分类选择器 -->
          <el-select v-model="blogForm.categoryId" placeholder="请选择分类" :disabled="loadingCategories">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <!-- 替换原有的el-input为v-md-editor -->
        <v-md-editor v-model="blogForm.content" height="400px" placeholder="请输入Markdown格式的博客内容"></v-md-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleUpdate">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
// 移除本地Markdown编辑器导入和配置
import { useRouter, useRoute } from 'vue-router'
import { blogApi } from '@/api/blogApi'
import { blogFormRules } from '@/utils/formRules'
import { categoryApi } from '@/api/categoryApi'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const blogId = route.params.id
const blogFormRef = ref(null);
const blogForm = ref({
  title: '',
  categoryId: null, // 将categoryId改为category对象
  category: null,
  content: ''
})
const categories = ref([])
const loadingCategories = ref(false)
const loading = ref(false)
// 移除本地rules定义

// 更新博客
const handleUpdate = async () => {
  if (!blogFormRef.value) return
  if (!blogFormRef.value.validate()) return
  loading.value = true
  try {
    await blogFormRef.value.validate()
    // 手动设置category对象
    loading.value = true
    blogForm.value.category = categories.value.find(category => category.id === blogForm.value.categoryId)
    console.log("输出分类" ,blogForm.value.categoryId)
    await blogApi.updateBlog(blogId, blogForm.value)
    router.push('/blogs')
  } catch (error) {
    console.error('更新博客失败:', error)
  } finally {
    loading.value = false
  }
}

const cancel = () => {
  router.push('/blogs')
}

// 修改onMounted钩子中的数据处理
onMounted(async () => {
  loadingCategories.value = true
  try {
    const [blogResponse, categoriesResponse] = await Promise.all([
      blogApi.getBlog(blogId),
      categoryApi.getAllCategories()
    ])
    blogForm.value = {
      ...blogResponse.data,
      categoryId: blogResponse.data.category?.id || null // 提取ID而非整个对象
    }
    categories.value = categoriesResponse.data
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loadingCategories.value = false
  }
})

// // 配置Markdown编辑器
// VMdEditor.use(vuepressTheme, { Prism })

// 添加组件卸载时的清理逻辑
onUnmounted(() => {
  // 清空表单数据
  blogForm.value = { title: '', category: null, content: '' }
  // 重置编辑器实例
  if (blogFormRef.value) {
    blogFormRef.value.resetFields()
  }
})
</script>

<style scoped>
.blog-form-container {
  max-width: 800px;
  margin: 0 auto;
}

.blog-form-header {
  margin-bottom: 20px;
}

.blog-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}
</style>